package com.xnyzc.lhy.order.service.impl.order;

import com.alibaba.fastjson.JSONObject;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.component.sms.AliCloudSMSUtils;
import com.xnyzc.lhy.common.constant.AliCloudSmsConstant;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.entity.Qw;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.global.Configuration;
import com.xnyzc.lhy.common.penum.order.EOrderStatus;
import com.xnyzc.lhy.mis.entity.sidebar.OaSysOffice;
import com.xnyzc.lhy.order.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.order.entity.system.OaSysUser;
import com.xnyzc.lhy.order.entity.user.OaDUser;
import com.xnyzc.lhy.order.mapper.order.OaCOrderPersonalMapper;
import com.xnyzc.lhy.order.mapper.sidebar.OaSysOfficeMapper;
import com.xnyzc.lhy.order.mapper.system.OaSysUserMapper;
import com.xnyzc.lhy.order.mapper.user.OaDUserInfoMapper;
import com.xnyzc.lhy.order.mapper.user.OaDUserMapper;
import com.xnyzc.lhy.order.service.order.IOaCBookingOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

@Slf4j
@Service
public class OaCBookingOrderServiceImpl implements IOaCBookingOrderService {

    @Autowired
    private OaCOrderPersonalMapper oacOrderPersonalMapper;

    @Autowired
    private OaDUserMapper oaDUserMapper;

    @Autowired
    private OaDUserInfoMapper oaDUserInfoMapper;

    @Autowired
    private OaSysUserMapper oaSysUserMapper;

    @Autowired
    private OaSysOfficeMapper oaSysOfficeMapper;

    @Autowired
    private RedisCommon redisCommon;

    @Override
    public Rv checkOrderStatus() {
        //1.检查抢单延时任务队列
        //checkOrderHall();
        //2.检查出发前2小时延时任务队列
        checkOrderStart();
        //3.检查出发前1小时延时任务队列
        checkWarning1();
        //4.检查第二次3分钟报警提醒延时任务队列
//        checkWarning2();
//        //5.检查第三次3分钟报警提醒延时任务队列
//        checkWarning3();
        return Rv.wrap();
    }

    private void checkOrderHall() {
        Set<String> set = redisCommon.getFromZSet(RedisPrefixConstant.ORDER_TC_HALL, 0, System.currentTimeMillis());
        for (String key : set) {
            if (key != null) {
                if (redisCommon.delFromZSet(RedisPrefixConstant.ORDER_TC_HALL, key)) {
                    String[] strs = key.split(":");
                    String orderId = strs[strs.length - 1];

                    Qw personalQw = Qw.create();
                    personalQw.eq(OaCOrderPersonal.ORDER_NO, orderId);
                    personalQw.eq(OaCOrderPersonal.ORDER_STATUS, EOrderStatus.waitingResponse.getType());
                    OaCOrderPersonal personal = oacOrderPersonalMapper.selectOne(personalQw);
                    if (personal == null) {
                        //redisCommon.addToZSet(RedisPrefixConstant.ORDER_TC_HALL, key, System.currentTimeMillis());
                        log.info("无效订单-" + orderId);
                        continue;
                    }
                    //通知车头
                    OaSysOffice office = oaSysOfficeMapper.selectOne(Qw.create().eq(OaSysOffice.OFFICE_ID, personal.getOfficeId()));
                    sendWarningToManager(office.getPhone(), orderId, "120");
                } else {
                    //任务已被其他服务执行，不做任何处理
                    continue;
                }
            }
        }
    }

    private void checkOrderStart() {
        Set<String> set = redisCommon.getFromZSet(RedisPrefixConstant.ORDER_TC_ZSET2, 0, System.currentTimeMillis());
        for (String key : set) {
            if (key != null) {
                if (redisCommon.delFromZSet(RedisPrefixConstant.ORDER_TC_ZSET2, key)) {
                    String[] strs = key.split(":");
                    String orderId = strs[strs.length - 1];
                    OaCOrderPersonal personal = oacOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderId));
                    if (personal != null) {
                        //发送预警短信通知
                        OaDUser driver = oaDUserMapper.selectOne(Qw.create().eq(OaDUser.DRIVER_ID, personal.getDriverId()));
                        sendWarningToDriver(driver.getDriverPhone(), personal.getOrderNo(), "120");

                        long endTime = System.currentTimeMillis() + Configuration.DELAY_SERIOUS_WARNING;
                        redisCommon.addToZSet(RedisPrefixConstant.ORDER_TC_ZSET3, orderId, endTime);
                    }
                } else {
                    //任务已被其他服务执行，不做任何处理
                    continue;
                }
            }
        }
    }

    private void checkWarning1() {
        Set<String> set = redisCommon.getFromZSet(RedisPrefixConstant.ORDER_TC_ZSET3, 0, System.currentTimeMillis());
        for (String key : set) {
            if (key != null && redisCommon.delFromZSet(RedisPrefixConstant.ORDER_TC_ZSET3, key)) {
                String[] strs = key.split(":");
                String orderId = strs[strs.length - 1];
                OaCOrderPersonal personal = oacOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderId));
                if (personal != null) {
                    if (redisCommon.delFromZSet(RedisPrefixConstant.ORDER_TC_ZSET3, key)) {
                        OaDUser driver = oaDUserMapper.selectOne(Qw.create().eq(OaDUser.DRIVER_ID, personal.getDriverId()));
                        sendWarningToDriver(driver.getDriverPhone(), personal.getOrderNo(), "60");
                        OaSysUser manager = oaSysUserMapper.selectOne(Qw.create().eq(OaSysUser.SYS_USER_ID, driver.getCreateUser()));
                        sendWarningToManager(manager.getPhone(), personal.getOrderNo(), "60");
                    } else {
                        //任务已被其他服务执行，不做任何处理
                        continue;
                    }
                }
            }
        }
    }

    private void checkWarning2() {
        Set<String> set = redisCommon.getFromZSet(RedisPrefixConstant.ORDER_TC_ZSET4, 0, System.currentTimeMillis());
        for (String key : set) {
            if (key != null) {
                String[] strs = key.split(":");
                String orderId = strs[strs.length - 1];
                OaCOrderPersonal personal = oacOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderId));
                if (personal != null) {
                    if (redisCommon.delFromZSet(RedisPrefixConstant.ORDER_TC_ZSET4, key)) {
                        // 第2次3分钟间隔提醒
                        OaDUser driver = oaDUserMapper.selectOne(Qw.create().eq(OaDUser.DRIVER_ID, personal.getDriverId()));
                        sendWarningToDriver(driver.getDriverPhone(), personal.getOrderNo(), "57");
                        OaSysUser manager = oaSysUserMapper.selectOne(Qw.create().eq(OaSysUser.SYS_USER_ID, driver.getCreateUser()));
                        sendWarningToManager(manager.getPhone(), personal.getOrderNo(), "57");
                    } else {
                        //任务已被其他服务执行，不做任何处理
                        continue;
                    }
                }
            }
        }
    }

    private void checkWarning3() {
        Set<String> set = redisCommon.getFromZSet(RedisPrefixConstant.ORDER_TC_ZSET5, 0, System.currentTimeMillis());
        for (String key : set) {
            if (key != null) {
                String[] strs = key.split(":");
                String orderId = strs[strs.length - 1];
                OaCOrderPersonal personal = oacOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderId));
                if (personal != null) {
                    if (redisCommon.delFromZSet(RedisPrefixConstant.ORDER_TC_ZSET5, key)) {
                        // FIXME 第3次3分钟间隔则执行改派操作，如果转派失败则通知供应商处理
                        OaDUser driver = oaDUserMapper.selectOne(Qw.create().eq(OaDUser.DRIVER_ID, personal.getDriverId()));
                        OaSysUser manager = oaSysUserMapper.selectOne(Qw.create().eq(OaSysUser.SYS_USER_ID, driver.getCreateUser()));
                    } else {
                        //任务已被其他服务执行，不做任何处理
                        continue;
                    }
                }
            }
        }
    }

    /**
     * 发送预约订单超时短信提醒
     *
     * @param phone
     * @param orderId
     * @param minute
     */
    private void sendWarningToDriver(String phone, String orderId, String minute) {
        JSONObject smsJson = new JSONObject();
        smsJson.put("minute", minute);
        smsJson.put("orderId", orderId);
        try {
//            QCloudSMSUtils.sendMessage(phone, QCloudSmsConstant.BOOKING_ORDER_WARINING_MSG, smsJson);
            AliCloudSMSUtils.sendMessage(phone, AliCloudSmsConstant.DRIVER_BOOKING_ORDER_WARINING_MSG, smsJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送预约订单超时短信提醒
     *
     * @param phone
     * @param orderId
     * @param minute
     */
    private void sendWarningToManager(String phone, String orderId, String minute) {
        JSONObject smsJson = new JSONObject();
        smsJson.put("minute", minute);
        smsJson.put("orderId", orderId);
        try {
//            QCloudSMSUtils.sendMessage(phone, QCloudSmsConstant.BOOKING_ORDER_WARINING_MSG, smsJson);
            AliCloudSMSUtils.sendMessage(phone, AliCloudSmsConstant.MANAGER_BOOKING_ORDER_WARINING_MSG, smsJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
